<template>
    <LoadPannel @searchMore="searchMore">
        <div ref="refreshRef" class="refresh-div">
            <i class="iconfont icon-loading-full"></i>
        </div>
        <div ref="exploreRef">
            <MiniCard v-for="(item, index) in exploreCards" :info="item" :key="item.id" @onImgLoaded="addImgCount">
            </MiniCard>
        </div>
    </LoadPannel>

</template>

<script setup>
import { ref, reactive, onMounted, watch, toRefs, nextTick } from 'vue'
import MiniCard from '@/components/MiniCard.vue'
import LoadPannel from "@/components/LoadPannel.vue"
import { exploreCardsMock } from '../../mock/homeData'
import computeWaterFallFlow from '../../utils/pubuliu'
import useHooks from '@/hooks/useHooks';
//使用toRefs避免丢失响应式数据
const { isRefresh } = toRefs(useHooks.state)
const { changeRefresh } = useHooks
//瀑布流
let exploreCards = reactive([])
let imgLen
const initData = async () => {
    let res = await exploreCardsMock()
    exploreCards.splice(0, exploreCards.length)
    nextTick(() => {
        imgLen = res.length //记录总图片
        res.forEach(item => {
            exploreCards.push(item)
        })
    })
}
initData();

//瀑布流计算每个card的位置
const exploreRef = ref(null)
//计算card中的图片是否加载完毕
let imgCount = 0
const addImgCount = () => {
    imgCount++
    if (imgCount === imgLen) {
        //开始计算瀑布流
        //...
        computeWaterFallFlow(exploreRef.value)
    }
}

//加载更多
const searchMore = async (callback) => {
    let res = await exploreCardsMock(5)
    res.forEach(item => {
        exploreCards.push(item)
    })
    imgLen = exploreCards.length
    callback ? callback() : ''
}

const refreshRef = ref(null)

const exploreRefresh = async () => {
    exploreRef.value.parentNode.parentNode.scrollTop = 0
    refreshRef.value.style.height = '100px'
    refreshRef.value.style.transition = 'all .3s linear'
    imgCount = 0
    await initData()
    refreshRef.value.style.height = '0px'
    setTimeout(() => {
        refreshRef.value.style.transition = ''
    }, 300)
}

watch(() => isRefresh.value, async (newValue, oldValue) => {
    //如果inRefresh为true刷新方法
    if (newValue) {
        await exploreRefresh()
        changeRefresh(false)
    }
})

onMounted(() => {
    exploreRefresh()
})
</script>

<style lang="scss" scoped>
.refresh-div {
    height: 0;
    width: 100%;
    overflow: hidden;
    @include flexcc;

    i {
        color: rgb(154, 154, 154);
        animation: rotate .8s linear infinite;
    }
}
</style>